﻿using EOH.IoTCard.CMCC;
using EOH.IoTCard.UPIoT;

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;

using System.Net.Http;

namespace System
{
    /// <summary>IServiceCollection 扩展方法</summary>
    public static class ServiceCollectionExtension
    {
        /// <summary>注入 中国移动 SDK</summary>
        public static IServiceCollection AddCmccService(this IServiceCollection service, Action<CmccOptions> setupAction)
        {
            if (service is null) { throw new ArgumentNullException(nameof(service)); }
            if (setupAction is null) { throw new ArgumentNullException(nameof(setupAction)); }
            var name = typeof(CmccService).FullName;
            service.AddHttpClient(name ?? string.Empty, client =>
            {
                client.BaseAddress = new Uri("https://api.iot.10086.cn");
                client.DefaultRequestHeaders.UserAgent.ParseAdd(nameof(CmccService));
                client.DefaultRequestHeaders.Accept.ParseAdd("application/json; charset=utf-8");
            });
            var opt = new CmccOptions();
            setupAction(opt);
            service.TryAddSingleton(sp => new CmccService(sp.GetService<IHttpClientFactory>(), opt));
            return service;
        }
        /// <summary>注入 UPIoT SDK</summary>
        public static IServiceCollection AddUPIoTService(this IServiceCollection service, Action<UPIoTOptions> setupAction)
        {
            if (service is null) { throw new ArgumentNullException(nameof(service)); }
            if (setupAction is null) { throw new ArgumentNullException(nameof(setupAction)); }
            var name = typeof(UPIoTService).FullName;
            service.AddHttpClient(name ?? string.Empty, client =>
            {
                client.BaseAddress = new Uri("http://ec.upiot.net");
                client.DefaultRequestHeaders.UserAgent.ParseAdd(nameof(UPIoTService));
                client.DefaultRequestHeaders.Accept.ParseAdd("application/json; charset=utf-8");
            });
            var opt = new UPIoTOptions();
            setupAction(opt);
            service.TryAddSingleton(sp => new UPIoTService(sp.GetService<IHttpClientFactory>(), opt));
            return service;
        }
    }
}
